package gui;

import dao.FileMeta;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.stage.DirectoryChooser;
import javafx.stage.Window;
import service.SearchService;

import javax.naming.InitialContext;
import java.io.File;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @author: cheng
 * @date: 2023/7/10 15:44
 * @description:
 */
public class GUIController implements Initializable {

    @FXML
    private GridPane gridPane;

    @FXML
    private Button button;

    @FXML
    private Label label;

    @FXML
    private TextField textField;

    @FXML
    private TableView<FileMeta> tableView;

    private SearchService searchService = null;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        //输入框添加监听器
        textField.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                //oldValue输入框修改之前的值, newValue修改后的值
                freshTable(newValue);
            }

        });
    }

    public void freshTable(String pat){
        if(searchService == null){
            System.out.println("searchService 未初始化,不能查询");
            return;
        }
        //将之前就的数据消除,需要拿到tableViw的集合类
        ObservableList<FileMeta> fileMetas = tableView.getItems();
        //清空
        fileMetas.clear();
        List<FileMeta> results = searchService.search(pat);
        //将查询结果添加到tableViw中
        fileMetas.addAll(results);
    }

    //鼠标点击
    public void choose(MouseEvent mouseEvent){
        DirectoryChooser directoryChooser = new DirectoryChooser();
        Window window = gridPane.getScene().getWindow();
        File file = directoryChooser.showDialog(window);
        if (file == null){
            System.out.println("当前选择路径为空");
            return;
        }
        System.out.println(file.getAbsolutePath());
        //用户选择的路径显示到label上
        label.setText(file.getAbsolutePath());

        //判断是否是首次扫描,非空就不是首次扫描
        if (searchService != null){
            searchService.shutDown();
        }
        //将对应数据加入到数据库中
        searchService = new SearchService();
        searchService.init(file.getAbsolutePath());
    }
}
